//
//  AppDelegate+Notification.m
//  NewProject
//
//  Created by Xu小波 on 2017/11/28.
//  Copyright © 2017年 FZ. All rights reserved.
//

#import "AppDelegate+Notification.h"

#import "JPUSHService.h"
#import "JPushManager.h"

@implementation AppDelegate (Notification)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [self _appdelegateNotificationHook];
    });
}

+ (void)_appdelegateNotificationHook {

    swizzleInstanceMethodWithClass([self class],
                                   @selector(application:didRegisterForRemoteNotificationsWithDeviceToken:),
                                   @selector(lx_application:didRegisterForRemoteNotificationsWithDeviceToken:));
    swizzleInstanceMethodWithClass([self class],
                                   @selector(application:didFailToRegisterForRemoteNotificationsWithError:),
                                   @selector(lx_application:didFailToRegisterForRemoteNotificationsWithError:));
    
    swizzleInstanceMethodWithClass([self class],
                                   @selector(application:didReceiveRemoteNotification:fetchCompletionHandler:),
                                   @selector(lx_application:didReceiveRemoteNotification:fetchCompletionHandler:));
}

- (void)lx_application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
}

- (void)lx_application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
    
}


//iOS7及以上系统，收到通知
- (void)lx_application:(UIApplication *)application
        didReceiveRemoteNotification:(NSDictionary *)userInfo
        fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [JPUSHService handleRemoteNotification:userInfo];
    
    //通知处理
    [[JPushManager manager] dealNotification:userInfo];
    
    completionHandler(UIBackgroundFetchResultNewData);
}


void swizzleInstanceMethodWithClass(Class class,
                                    SEL originalSelector,
                                    SEL swizzledSelector) {
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    
    if (class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))) {
        
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }else {
        
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

@end
